//
//Copyright GX. Yuan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @file net.go
 * @brief Leetcode 剑指Offer 第二版
 * @details 剑指 Offer 25. 合并两个排序的链表
 * @author GX. Yuan  any question please send mail to yuanguanxu@qq.com
 * @date 2021-6-28
 * @version V1.0
 * @attention 硬件平台: windows 10 家庭版
 * SDK版本：Go 1.16.5
 * IDE版本：GoLand 2020.2.3
 */
package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
	// 初始化一个伪装的头部
	// 链表通常会自动初始化一个没用的头部，主要的作用是就第一个元素的使用，需要对一个元素进行能够特殊处理
	var root ListNode  // 初始化一个根部变量;
	l3:=&root
	// 都不为空，那么运行，只有一个nil，有一个循环结束了
	for l1 != nil && l2 != nil {
		if l2.Val>l1.Val { // 找到更小的连接上
			l3.Next=l1
			l1=l1.Next
			l3=l3.Next
		}else {
			l3.Next=l2
			l2=l2.Next
			l3=l3.Next
		}
	}
	if l1 == nil {
		l3.Next=l2
	}
	if l2 == nil {
		l3.Next= l1
	}
	return root.Next
}

func main() {
	l1:=&ListNode{1,&ListNode{2,&ListNode{4,nil}}}
	l2:=&ListNode{1,&ListNode{3,&ListNode{4,nil}}}
	root:=mergeTwoLists(l1,l2)
	for root!=nil {
		fmt.Println(root.Val)
		root=root.Next
	}
}
